package com.gbq.qimo.servlet.filter;

import com.sun.net.httpserver.HttpExchange;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.dsig.spec.XPathType;
import java.io.IOException;

/**
 * @ClassName UserFilter
 * @Description TODO
 * @Author guobenqi
 * @Date 2021/6/6 10:32
 */
@WebFilter(urlPatterns = "/*")
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;


        String a=httpServletRequest.getRequestURI();
        System.out.println("1："+a);
        if(a.contains("/login")||a.contains("/register")|| a.contains("/register.jsp")|| a.contains("/index.jsp")||a.contains("/css/") || a.contains("/js/") || a.contains("/image/")|| a.contains("/checkCodeServlet")||a.contains("PNG") ){
            //如果发现是css或者js文件，直接放行
            System.out.println("2："+a);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");
         if (user == null){

             httpServletRequest.setAttribute("login_msg","您还未登录,请先登录!");
             httpServletRequest.getRequestDispatcher("/").forward(servletRequest,servletResponse);
//             ((HttpServletResponse)servletResponse).sendRedirect("/");
             return;
         }else{
             filterChain.doFilter(servletRequest,servletResponse);
             return;
         }
    }

    @Override
    public void destroy() {

    }
}
